<?php

namespace app\common\model;

use app\helpers\Common;
use app\libs\traits\BaseModelTrait;

use think\model\concern\SoftDelete;

class Article extends Base
{
    /**
     * Base Model Trait
     */
    use BaseModelTrait;

    //use SoftDelete;

    protected $deleteTime = 'deleted_at';

    // 软删除字段默认值
    protected $defaultSoftDelete = 0;

    // 当前模型名称 不带前缀
    protected $name = 'articles';

    public $pk = 'id';

    public static $tabeName = 'articles';


    /**
     * Set sorting attribute
     *
     * @param $value
     * @return int
     */
    public function setSortingAttr($value)
    {
        return !empty($value) ? $value : 0;
    }

    protected function getContentAttr($data)
    {
        if (!$data) {
            return '';
        }

        return htmlspecialchars_decode($data);
    }

    protected function getPostTimeAttr($date)
    {
        if (!$date) {
            return '';
        }
        return date('Y-m-d H:i:s', $date);
    }

    public static function _after_insert($data)
    {
        // 封面图
        if (isset($data['cover_img']) && !empty($data['cover_img'])) {
            File::where('file_url', $data['cover_img'])->update(['related_id' => $data['id'], 'related_table' => self::$tabeName, 'tag' => 'single', 'status' => 1]);
        }
        // 图片集
        if (isset($data['images']) && !empty($data['images'])) {
            $images = $data['images'];
            if (!is_array($images)) {
                $images = explode(',', $images);
            }
            foreach ($images as $key => $image) {
                File::where('file_url', $image)->update(['related_id' => $data['id'], 'related_table' => self::$tabeName, 'tag' => 'images', 'sorting' => $key, 'status' => 1]);
            }
        }
        // 附件
        if (isset($data['files']) && !empty($data['files'])) {
            $files = $data['files'];
            if (!is_array($files)) {
                $files = explode(',', $files);
            }
            foreach ($files as $key => $file) {
                File::where('file_url', $file)->update(['related_id' => $data['id'], 'related_table' => self::$tabeName, 'tag' => 'files', 'sorting' => $key, 'status' => 1]);
            }
        }
    }

    public static function _after_update($data)
    {
        // 封面图
        if (isset($data['cover_img']) && !empty($data['cover_img'])) {
            // 处理删除掉的文件
            File::where(['related_id' => $data['id'], 'related_table' => self::$tabeName, 'tag' => 'single'])->where('file_url', '<>', $data['cover_img'])->update(['status' => 0]);

            File::where('file_url', $data['cover_img'])->update(['related_id' => $data['id'], 'related_table' => self::$tabeName, 'tag' => 'single', 'status' => 1]);
        }
        // 图片集
        if (isset($data['images']) && !empty($data['images'])) {
            // 处理删除掉的文件
            File::where(['related_id' => $data['id'], 'related_table' => self::$tabeName, 'tag' => 'images'])->whereNotIn('file_url', $data['images'])->update(['status' => 0]);

            $images = $data['images'];
            if (!is_array($images)) {
                $images = explode(',', $images);
            }
            foreach ($images as $key => $image) {
                File::where('file_url', $image)->update(['related_id' => $data['id'], 'related_table' => self::$tabeName, 'tag' => 'images', 'sorting' => $key, 'status' => 1]);
            }
        }
        // 附件
        if (isset($data['files']) && !empty($data['files'])) {
            // 处理删除掉的文件
            File::where(['related_id' => $data['id'], 'related_table' => self::$tabeName, 'tag' => 'files'])->whereNotIn('file_url', $data['files'])->update(['status' => 0]);

            $files = $data['files'];
            if (!is_array($files)) {
                $files = explode(',', $files);
            }
            foreach ($files as $key => $file) {
                File::where('file_url', $file)->update(['related_id' => $data['id'], 'related_table' => self::$tabeName, 'tag' => 'files', 'sorting' => $key, 'status' => 1]);
            }
        }
    }

    public static function _after_delete($data)
    {
        if (is_numeric($data) || is_string($data)) {
            $data = self::find($data);
        }

        // 封面图
        if (isset($data['cover_img']) && !empty($data['cover_img'])) {
            File::where('file_url', $data['cover_img'])->update(['status' => 0]);
        }
        // 图片集
        if (isset($data['images']) && !empty($data['images'])) {
            $images = $data['images'];
            File::whereIn('file_url', $images)->update(['status' => 0]);
        }
        // 附件
        if (isset($data['files']) && !empty($data['files'])) {
            $files = $data['files'];
            File::whereIn('file_url', $files)->update(['status' => 0]);
        }
    }

    /**
     * 格式化列表数据
     */
    public static function formatDatas($list, $params = '')
    {
        foreach ($list as &$item) {
            $item = (new self())->formatItem($item, $params);
        }

        return $list;
    }

    /**
     * 格式化单个数据
     */
    public static function formatItem($item, $params = '')
    {
        if (!$item) {
            return '';
        }

        // 封面图
        $item['full_cover_img'] = full_file_url($item['cover_img']);
        // 图片集
        $imageList = File::where(['related_id' => $item['id'], 'related_table' => self::$tabeName, 'tag' => 'images', 'status' => 1])->column('file_url');
        $images = [];
        foreach ($imageList as $image) {
            $images[] = [
                'filepath' => $image,
                'url' => asset(config('path.upload_path') . $image)
            ];
        }
        $item['images'] = $images;
        // 附件
        $fileList = File::where(['related_id' => $item['id'], 'related_table' => self::$tabeName, 'tag' => 'files', 'status' => 1])->field('file_url, file_name')->select();
        $files = [];
        foreach ($fileList as $file) {
            $files[] = [
                'name' => $file['file_name'],
                'filepath' => $file['file_url'],
                'url' => asset(config('path.upload_path') . $file['file_url'])
            ];
        }
        $item['files'] = $files;

        if (isset($params['format_source']) && $params['format_source'] == 'backend') {
            // 状态
            switch ($item['status']) {
                case 1:
                    $item['status_name'] = '显示';
                    break;
                case 2:
                    $item['status_name'] = '隐藏';
                    break;
                case 90:
                    $item['status_name'] = '删除';
                    break;
                default: break;
            }

            // 分类
            $category = ArticleCate::where('id', $item['cate_id'])->field('name')->find();
            $item['cate_name'] = $category['name'];
        }

        return $item;
    }
}
